import { Input } from 'antd';
import { SizeType } from 'antd/lib/config-provider/SizeContext';
import { InputProps, PasswordProps, TextAreaProps } from 'antd/lib/input';
import classNames from 'classnames';
import { ChangeEventHandler } from 'react';
import styles from './index.module.less';

const TextArea = Input.TextArea;
const Password = Input.Password;

export interface InputLimitProps {
  maxLength?: number;
  value?: any;
  showTip?: boolean;
  singleBorder?: boolean;
  inputType?: 'textarea' | 'password' | 'input';
  inputProps?: TextAreaProps | InputProps | PasswordProps;
  className?: string;
  placeholder?: string;
  allowClear?: boolean;
  bordered?: boolean;
  size?: SizeType;
  prefix?: any;
  suffix?: any;
  onChange?: ChangeEventHandler;
}

/**
 * 输入限制组件
 * @param props
 */
export default function InputLimit(props: InputLimitProps) {
  const {
    maxLength,
    value,
    inputType,
    className,
    singleBorder,
    allowClear,
    size,
    showTip,
    bordered,
    placeholder,
    prefix,
    suffix,
    onChange,
  } = props;
  const valueLength = (value && value.length) || 0;
  let InputComp;
  switch (inputType) {
    case 'textarea':
      InputComp = TextArea;
      break;
    case 'password':
      InputComp = Password;
      break;
    default:
      InputComp = Input;
      break;
  }

  const cls = classNames(className, styles.inputContainer, {
    [styles.singleBorder]: singleBorder,
  });

  return (
    <div className={styles.container}>
      <div className={cls}>
        <InputComp
          allowClear={allowClear}
          maxLength={maxLength}
          size={size}
          bordered={bordered}
          placeholder={placeholder}
          prefix={prefix}
          suffix={suffix}
          onChange={onChange}
          value={value}
        />
        {showTip && (
          <div className={styles.length}>
            <span className={styles.valueLength}>{valueLength}</span>
            <span className={styles.separated}>/</span>
            <span className={styles.maxLength}>{maxLength || '无限制'}</span>
          </div>
        )}
      </div>
      {singleBorder && <div className={styles.divider}></div>}
    </div>
  );
}
